﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Http2TcpWcfService
{
    // NOTE: If you change the class name "Http2TcpService" here, you must also update the reference to "Http2TcpService" in Web.config.
    public class Http2TcpService : IHttp2TcpService
    {
        public Http2TcpService()
        {
            p_CheckDisposeList = _CheckDisposeList;
        }

        public System.Timers.Timer p_CheckDisposeList;

        public static readonly TcpMappingCollection Mapping = new TcpMappingCollection();

        public static readonly LinkedList<TcpMappingItem> DisposeList = new LinkedList<TcpMappingItem>();

        static readonly System.Timers.Timer _CheckDisposeList = new System.Timers.Timer(30000) { Enabled = false  };
        static public System.Timers.Timer CheckDisposeList
        {
            get 
            {
                if (_CheckDisposeList.Enabled==false  )
                {
                    _CheckDisposeList.Elapsed +=new System.Timers.ElapsedEventHandler(_CheckDisposeList_Elapsed);
                    _CheckDisposeList.Enabled = true;
                }
                return CheckDisposeList;
            }
            set 
            { }
        
        }

        static void _CheckDisposeList_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            List<LinkedListNode<TcpMappingItem>> ls = new List<LinkedListNode<TcpMappingItem>>();
            var nd = DisposeList.First;
            while (nd.Next != null)
            {
                if (nd.Value.LastActive.AddSeconds(60) < DateTime.Now || nd.Value.TcpStream ==null  )
                {
                    nd.Value.Dispose();
                    ls.Add(nd);
                }
            

            }

            ls.ForEach(o => o.List.Remove(o));




        }
  
         

        #region IHttp2TcpService Members

        public byte[] Send(string server, int port, byte[] binaryBuffer, ref Guid connectionKey)
        {
            TcpMappingItem itm ;
            if  ( !Mapping.TryGetValue (connectionKey , out itm ))
            {
                itm = TcpMappingItem.Create(connectionKey,server, port);
            
            }
            if (itm == null)
            {
                throw new Exception("连接失败或者结束");
            }

            itm.SendBytes(binaryBuffer);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] bts;
            while (itm.ReceiveBytes(out bts))
            {
                ms.Write(bts, 0, bts.Length); 
            }

            return ms.ToArray();


        }

        #endregion
    }
}
